//
//  UserModel.m
//  youyue
//
//  Created by oceans on 2018/8/16.
//

#import "UserModel.h"
#import "HttpRequest.h"
#import "AppDelegate.h"
#import "TipManager.h"
#import "Utility.h"

@interface UserModel ()

@property (copy, nonatomic) LoginSuccessBlock thirdLoginSuccess;
@property (copy, nonatomic) LoginFailedBlock thirdLoginFailed;
@end

@implementation UserCompanyModel

- (instancetype)initWithDic:(NSDictionary *)dic {
    
    self = [super init];
    if (self) {
        _type = dic[@"type"];
        _name = dic[@"name"];
        _address = dic[@"address"];
    }
    return self;
}

@end

@implementation LoginUser

- (instancetype)initWithDic:(NSDictionary *)dic {
    self = [super init];
    if (self) {
        [self setup:dic];
    }
    return self;
}

- (void)setup:(NSDictionary *)dic {
    
    _avatar = [dic objectForKey:@"avatar"];
    __id = [[dic objectForKey:@"id"] intValue];
    _name = [dic objectForKey:@"name"];
    _company = [[UserCompanyModel alloc] initWithDic:dic[@"company"]];
}

@end

@interface UserModel ()


@end

static UserModel *shared;

@implementation UserModel

+ (instancetype)shared {
    
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        shared = [[UserModel alloc] init];
    });
    return shared;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        shared = [super allocWithZone:zone];
    });
    return shared;
}

- (id)copyWithZone:(NSZone *)zone {
    return shared;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self checkUser];
    }
    return self;
}

- (void)checkUser {
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSData *data = [def objectForKey:@"klogin_user_dic_data"];
    NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    if (dic) {
        self.loginUser = [[LoginUser alloc] initWithDic:dic];
        self.hasLogin = YES;
        self.userInfo = dic;
        [self autoLogin];
    }
}

- (void)cacheUser:(NSDictionary*)dic {
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
    [def setObject:data forKey:@"klogin_user_dic_data"];
    [def synchronize];
}

- (void)loginWithCode:(NSString *)code username:(NSString *)username successBlock:(LoginSuccessBlock)successBlock {
    
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:kmobile_login paras:@{@"phone": username, @"code": code} showProgress:YES successful:^(id  _Nullable result) {
        [[NSUserDefaults standardUserDefaults] setObject:result[@"datas"][@"token"] forKey:ktoken];
        [weakself loginWithDic:[result objectForKey:@"datas"][@"user"]];
        if (successBlock) {
            successBlock();
        }
    } failed:^(int code, NSString * _Nullable errMsg) {
        NSLog(@"");
    }];
}

- (void)getCodeWithPhoneNumber:(NSString *)phone scope:(NSString *)scope successBlock:(LoginSuccessBlock)successBlock failedBlock:(LoginFailedBlock)failedBlock{
    
    [HttpRequest postURL:kget_code paras:@{@"phone": phone, @"type": scope} showProgress:NO successful:^(id  _Nullable result) {
        if (successBlock) {
            successBlock();
        }
    } failed:^(int code, NSString *errMsg) {
        if (failedBlock) {
            failedBlock();
        }
    }];
}

- (void)autoLogin {
    
//    __weak typeof(self) weakself = self;
//    [HttpRequest getURL:kauto_login paras:nil showProgress:NO successful:^(id  _Nullable result) {
//        [weakself loginWithDic:[result objectForKey:@"data"]];
//    } failed:^(int code, NSString *errMsg) {
//        [weakself clearWhenLogout];
//    }];
}

- (void)loginWithDic:(NSDictionary *)userInfo {
    if (!(userInfo == nil || (NSNull*)userInfo == [NSNull null])) {
        self.loginUser = [[LoginUser alloc] initWithDic:userInfo];
        self.userInfo = userInfo;
        [self cacheUser:userInfo];
        self.hasLogin = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:klogin_notification object:nil];
    }
}

- (void)clearWhenLogout {
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def removeObjectForKey:@"klogin_user_dic_data"];
    [def synchronize];
    self.hasLogin = NO;
    self.loginUser = nil;
    [[NSNotificationCenter defaultCenter] postNotificationName:klogin_notification object:nil];
}

- (void)logoutWith401 {
    
    if (!self.hasLogin) {
        return;
    }
    [[(AppDelegate*)[UIApplication sharedApplication].delegate root].root popToRootViewControllerAnimated:YES];
    [self clearWhenLogout];
}

- (void)logoutSuccessBlock:(LoginSuccessBlock)successBlock {
    
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:klogout paras:nil showProgress:YES successful:^(id  _Nullable result) {
        
        [weakself clearWhenLogout];
        if (successBlock) {
            successBlock();
        }
    } failed:^(int code, NSString *errMsg) {
        
    }];
}

@end
